package com.projectzqjz.parttimework.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.projectzqjz.parttimework.App;
import com.projectzqjz.parttimework.R;
import com.projectzqjz.parttimework.entity.PartBaseEntity;
import com.projectzqjz.parttimework.net.MyCallback;
import com.projectzqjz.parttimework.net.NoValidationTask;
import com.projectzqjz.parttimework.utils.AppConfig;
import com.projectzqjz.parttimework.utils.NewsToastUtils;
import com.projectzqjz.parttimework.utils.PermissionUtils;
import com.projectzqjz.parttimework.utils.SPUtils;
import com.projectzqjz.parttimework.utils.SystemUtils;
import com.squareup.picasso.Picasso;

import java.lang.ref.WeakReference;

import retrofit2.Response;


/**
 * 欢迎页
 */
public class WelActivity extends AppCompatActivity {
    //定义需要申请的相关权限
    private final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE//读取手机状态码
    };
    //    Manifest.permission.READ_PHONE_STATE,
//    Manifest.permission.ACCESS_FINE_LOCATION,
//    Manifest.permission.WAKE_LOCK,
//    Manifest.permission.WRITE_CONTACTS,
//    Manifest.permission.WRITE_EXTERNAL_STORAGE
    private MyHandler myHandler;

    private ImageView wel_bg;

    @SuppressLint("MissingSuperCall")
    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        setContentView(R.layout.activity_wel);
        wel_bg = (ImageView) findViewById(R.id.wel_bg);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            View decorView = window.getDecorView();
            decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                @TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
                @Override
                public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    return defaultInsets.replaceSystemWindowInsets(
                            defaultInsets.getSystemWindowInsetLeft(),
                            0,
                            defaultInsets.getSystemWindowInsetRight(),
                            defaultInsets.getSystemWindowInsetBottom());
                }
            });
            ViewCompat.requestApplyInsets(decorView);
            //将状态栏设成透明，如不想透明可设置其他颜色
            window.setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
        }
        myHandler = new MyHandler(this);
//        getRatio();

//        getConfig();
        getPermission();

    }

    //保存数据
    private void saveConfig(JSONObject jsonObject) {
        AppConfig.getInstance(App.getContext()).set("img_home_card1", jsonObject.getString("img_home_card1"));
        AppConfig.getInstance(App.getContext()).set("img_home_card2", jsonObject.getString("img_home_card2"));
        AppConfig.getInstance(App.getContext()).set("img_person_banner", jsonObject.getString("img_person_banner"));//个人中心banner
        AppConfig.getInstance(App.getContext()).set("icon_featured_card1", jsonObject.getString("icon_featured_card1"));
        AppConfig.getInstance(App.getContext()).set("icon_featured_card2", jsonObject.getString("icon_featured_card2"));
        AppConfig.getInstance(App.getContext()).set("icon_featured_card3", jsonObject.getString("icon_featured_card3"));
        AppConfig.getInstance(App.getContext()).set("icon_featured_card4", jsonObject.getString("icon_featured_card4"));
        AppConfig.getInstance(App.getContext()).set("img_home_card2_2", jsonObject.getString("img_home_card2_2"));
        AppConfig.getInstance(App.getContext()).set("img_home_card1_1", jsonObject.getString("img_home_card1_1"));
        AppConfig.getInstance(App.getContext()).set("job_detail", jsonObject.getString("job_detail"));
        AppConfig.getInstance(App.getContext()).set("company_detail", jsonObject.getString("company_detail"));
        AppConfig.getInstance(App.getContext()).set("user_agreement", jsonObject.getString("user_agreement"));
        AppConfig.getInstance(App.getContext()).set("urivacy_protocol", jsonObject.getString("urivacy_protocol"));
        AppConfig.getInstance(App.getContext()).set("pesume_preview", jsonObject.getString("pesume_preview"));
        AppConfig.getInstance(App.getContext()).set("business_coop", jsonObject.getString("business_coop"));
        getPermission();
    }

    //    获取系统配置参数
    private void getConfig() {
        NoValidationTask.getApiService().getPartConfig().enqueue(new MyCallback<PartBaseEntity>(WelActivity.this) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                JSONObject jsonObject = JSON.parseObject((String) response.body().getData());
                saveConfig(jsonObject);
            }

            @Override
            protected void onFailure(Throwable t) {
                NewsToastUtils.showToast(App.getContext(), "拉取配置信息失败！");
            }
        });
    }

    /**
     * 获取屏幕分辨率
     */
    private void getRatio() {
        int xdpi = Math.round(getResources().getDisplayMetrics().ydpi);
        NoValidationTask.getApiService().getWelBG().enqueue(new MyCallback<PartBaseEntity>(WelActivity.this) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                Display display = getWindowManager().getDefaultDisplay();

                Point point = new Point();

                display.getSize(point);

//                int width = point.x;

                int height = point.y;

                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONObject jsonObject = JSON.parseObject(jsonStr);
                String ppi_1 = jsonObject.getString("320x480");
                String ppi_2 = jsonObject.getString("400x800");
                String ppi_3 = jsonObject.getString("720x1280");
                String ppi_4 = jsonObject.getString("1080x1920");
                String ppi_5 = jsonObject.getString("1080x2340");
                if (height <= 1920) {
                    if (xdpi <= 160) {
                        Picasso.with(App.getContext()).load(ppi_1).into(wel_bg);
                    } else if (xdpi <= 240) {
                        Picasso.with(App.getContext()).load(ppi_2).into(wel_bg);
                    } else if (xdpi <= 320) {
                        Picasso.with(App.getContext()).load(ppi_3).into(wel_bg);
                    } else if (xdpi <= 480) {
                        Picasso.with(App.getContext()).load(ppi_4).into(wel_bg);
                    } else {
                        Picasso.with(App.getContext()).load(ppi_5).into(wel_bg);
                    }
                } else {
                    Picasso.with(App.getContext()).load(ppi_5).into(wel_bg);
                }

            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    /**
     * 获取系统参数
     */
    @SuppressLint("HardwareIds")
    private void getGlobalHeader(boolean isOpen) {
        //mac地址
        String mac = SPUtils.get(App.getContext(), "mac", "") + "";
        if ("".equals(mac)) {
            if (SystemUtils.openWifi(App.getContext())) {
                //表示已经打开wifi了
                mac = SystemUtils.getUniqueIdentifier(App.getContext());
            } else {
                SPUtils.put(App.getContext(), "mac", "02:00:00:00:00:00");//唯一标识
            }
        }
        //手机的imei
        String imei;
        if (isOpen) {
            imei = SystemUtils.getIMEI();
        } else {
            imei = "";
        }
        //androidId
        String androidId = SystemUtils.getAndroidId();
        //最后的唯一标识
        String unique = androidId + Build.SERIAL;
        SPUtils.put(App.getContext(), "uniqueIdentifier", unique);
        myHandler.sendEmptyMessageDelayed(0, 1000);
    }

    //打开其他的浏览器
//    private void checkVersion() {
//        Task.getApiService().checkNewsVersion().enqueue(new MyCallback<NewsBaseEntity>(WelActivity.this) {
//            @Override
//            protected void onSuccess(Response<NewsBaseEntity> response) {
//              if ("1".equals(response.body().getCode())){
//                  String downLoadUrl = AppConfig.getInstance(App.getContext()).get("downLoadUrl");
//                  String jsonStr = JSONObject.toJSONString(response.body().getData());
//                  JSONObject jsonObject = JSONObject.parseObject(jsonStr);
//                  String str=jsonObject.getString("android");
//                  JSONObject jsonObject_1 = JSONObject.parseObject(str);
//                  String remoteVersion=jsonObject_1.getString("version");
//                  String versionName = SystemUtils.getLocalVersionName(App.getContext());
//                  if (!versionName.equals(remoteVersion)){
//                      new CenterDialog(R.layout.prompt_check_version,WelActivity.this).checkVersion(jsonObject_1.getString("remark"),downLoadUrl);
//                  }else {
//                      getPermission();
//                  }
//
//              }else {
//                  NewsToastUtils.showToast(App.getContext(),response.body().getMsg());
//              }
//            }
//
//            @Override
//            protected void onFailure(Throwable t) {
//                NewsToastUtils.showToast(App.getContext(),"网络请求失败！");
//            }
//        });
//    }

    /**
     * 获取相关权限
     */
    private void getPermission() {
        PermissionUtils.getInstance().checkPermissions(this, PERMISSIONS, permissionsResult);
    }

    //创建监听权限的接口对象
    PermissionUtils.IPermissionsResult permissionsResult = new PermissionUtils.IPermissionsResult() {
        @Override
        public void passPermissons() {
            //当提示申请权限时，全部通过，会走这里（6.0以下直接走这里）
//            myHandler.sendEmptyMessageDelayed(0, 1000);
            getGlobalHeader(true);
        }

        @Override
        public void forbitPermissons() {
            //只要有一个被拒绝，则会走这里，拒绝不在提醒，还是会走这里
//            myHandler.sendEmptyMessageDelayed(0, 1000);
            getGlobalHeader(false);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //回调结果
        PermissionUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    //静态内部类handler，防止内存泄漏
    private static class MyHandler extends Handler {

        private WeakReference<WelActivity> mActivity;

        private MyHandler(WelActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Activity act = mActivity.get();
            if (act != null) {
//                boolean isFirst = (boolean) SPUtil.get(act.getApplicationContext(),
//                        Constant.CommonInfo.IS_FIRST, true);
                //引导页去掉
                boolean isFirst = false;
//                if (isFirst) {//首次打开
//                    act.startActivity(new Intent(act, GuideActivity.class));
//                } else {//非首次打开
                //同意权限后进行获取系统参数
                //获取header信息


                act.startActivity(new Intent(act, MainActivity.class));
                act.finish();
//                try {
//                    if (UserUtils.checkLogin()) {
//                        act.startActivity(new Intent(act, MainActivity.class));
//                        act.finish();
//                    } else {
//                        act.startActivity(new Intent(act, NewsLoginActivity.class));
//                        act.finish();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myHandler != null)
            myHandler.removeCallbacksAndMessages(null);
    }
}
